package account

import (
	"hobby-mate/common"
	"hobby-mate/config/db"
	"hobby-mate/entity"
	"hobby-mate/util"
)

var baseCurd *common.BaseCURDImpl

func init() {
	baseCurd = common.CreateBaseCURDImpl(db.Db)
}

func GetUserTest(id int) (entity.Account, error) {
	var user entity.Account
	err := baseCurd.QueryById(id, &user)
	return user, err
}

// QueryUserByCondition 根据用户名和密码查询用户
func QueryUserByCondition(userName string, password string) (entity.Account, error) {
	var user entity.Account
	if err := baseCurd.QueryByCondition(&user, &entity.Account{Username: userName, Password: password}); err != nil {
		return entity.Account{}, err
	}
	return user, nil
}

// QueryUserByPageCondition 分页查询用户
// @param query 分页查询条件 页码和每页大小
// 条件：
// 1.账户ID 2.账户名 3.登录名
// 4.邮箱 5.电话号码 6.创建时间范围
// 7.更新时间范围
func QueryUserByPageCondition(query *common.PageQuery) (*common.PageResult, error) {
	// 值映射
	var user []entity.Account
	// 查询条件
	var accountInfo = QueryConditions{}
	var conditionIn map[string]interface{}
	if query.Condition != nil {
		//TODO:如果query.Condition的属性不符合QueryConditions的属性，会报错 该怎么办？
		//TODO:99%的情况下，Condition类型不会全传
		accountInfo = query.Condition.(QueryConditions)
		//构造in查询条件
		conditionIn = map[string]interface{}{
			"createTimeRange": accountInfo.CreateTimeRange,
			"updateTimeRange": accountInfo.UpdateTimeRange,
		}
	}
	// 分页查询
	base := &common.PageBase{
		CurrentPage: query.CurrentPage,
		PageSize:    query.PageSize,
	}
	resultData, err := baseCurd.QueryByPageCondition(
		&user,
		&entity.Account{
			Username:    accountInfo.Username,
			LoginName:   accountInfo.LoginName,
			Email:       accountInfo.Email,
			PhoneNumber: accountInfo.PhoneNumber,
			AccountId:   accountInfo.AccountId,
		},
		conditionIn,
		base)
	if err != nil {
		return resultData, err
	}
	resultData.Data = user
	return resultData, nil
}

// AddUser 添加用户
func AddUser(userName string, password string) (string, error) {
	user := entity.Account{
		AccountId: util.NewIDGenerate().NextStrWithPrefix("ac-"),
		Username:  userName,
		Password:  password,
	}
	user.InsertSetBaseEntity()
	err := baseCurd.Insert(&user)
	if err != nil {
		return "mysql Error", err
	}
	return user.AccountId, err
}

func UpdateUser(account entity.Account) error {
	return db.Db.Model(&account).Where("id = ?", account.AccountId).Update("username", account.Username).Error
}

func DeletedById(id int) error {
	return db.Db.Where("id = ?", id).Delete(&entity.Account{}).Error
}
